package Java7_Concurrency_Cookbook.concurrent_collection_framework.atomic_array;

import java.util.concurrent.atomic.AtomicIntegerArray;

/**
 * Java还提供了另外一个原子数组类, 即AtomicLongArray
 * @author lixiangke
 * @date 2017/11/24
 */
public class Main {
    public static void main(String[] args) throws InterruptedException {
        final int THREADS = 100;
        AtomicIntegerArray vector = new AtomicIntegerArray(20);
        Incrementer incrementer = new Incrementer(vector);
        Decrementer decrementer = new Decrementer(vector);
        Thread threadIncrementer[] = new Thread[THREADS];
        Thread threadDecrementer[] = new Thread[THREADS];
        for (int i = 0; i < THREADS; i++) {
            threadIncrementer[i] = new Thread(incrementer);
            threadDecrementer[i] = new Thread(decrementer);
            threadIncrementer[i].start();
            threadDecrementer[i].start();
        }

        for (int i = 0; i < 100; i++) {
            threadIncrementer[i].join();
            threadDecrementer[i].join();
        }

        for (int i = 0; i < vector.length(); i++) {
            if (vector.get(i) != 0) {
                System.out.println("Vector[" + i + "] : " + vector.get(i));
            }
        }

        System.out.println("Main: End of the program!");
    }
}
